import axios from 'axios';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Session } from '/@/utils/storage';
import { Sign } from '/@/utils/sign';

// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_SERVER_URL as any,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' }
});

const globalLoading = {
	isLoading: false,
	elLoading: {} as any,
}

//打开加载层
const openLoading = () => {
	if(globalLoading.isLoading == false){
		const elLoading = ElLoading.service({
			lock: true,
			text: '正在努力加载中,请稍候...',
			background: 'rgba(0, 0, 0, 0.5)'
		});
		globalLoading.isLoading = true;
		globalLoading.elLoading = elLoading;
	}
}

//关闭加载层
const closeLoading = () => {
	setTimeout(() => {
		if(globalLoading.isLoading == true){
			if(globalLoading.elLoading && typeof globalLoading.elLoading.close == 'function'){
				globalLoading.elLoading.close();
			}
			globalLoading.isLoading = false;
			globalLoading.elLoading = {};
		}
	}, 500);
}

//跳转到登录页面
const logout = (res: any) => {
	Session.clear();
	ElMessage.error(res.data.msg || 'Unauthorized 请求身份未认证');
	ElMessageBox.alert('你已被登出，请重新登录，5秒后自动跳转登录页面', '提示', {'confirmButtonText' : '确定'}).then(() => {
		window.location.href = window.location.pathname;
	});
	setTimeout(() => {
		window.location.href = window.location.pathname;
	}, 5000);
}

// 添加请求拦截器
service.interceptors.request.use(
	(config: any) => {
		if (Session.get('token')) {
			config.headers.common['Authorization'] = `Bearer ${Session.get('token')}`;
		}
		if(Session.get('tenantId')){
			config.headers.common['X-Request-Tenant-Id'] = `${Session.get('tenantId')}`;
		}
		if(['post', 'put', 'delete', 'patch'].indexOf(config.method.toLowerCase()) > -1){
			openLoading();
		}
		//参数签名
		const { signature, secret, timestamp } = Sign.signature(config);
		config.headers.common['signature'] = signature;
		config.headers.common['secret'] = secret;
		config.headers.common['timestamp'] = timestamp;
		return config;
	},
	(error: any) => {
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(res: any) => {
		closeLoading();
		if(res.data?.code != 0 && res.data?.code != 200 && res.config?.responseType?.toLowerCase() != 'blob'){
			ElMessage.error(res.data.msg || res.statusText || '未知错误');
		}
		return res.data;
	},
	(error: any) => {
		closeLoading();
		const res = error.response;
		if(res?.status == 401){
			logout(res);
			return res.data;
		}else{
			ElMessage.error(res?.data?.msg || res?.statusText || '未知错误');
			return Promise.reject(error);
		}
	}
);

export default service;
